{include file="public/header-static"/}

{include file="public/sidebar"/}
<div id="main">

    {include file="public/header"/}

    <main class="main-content">

        <div class="container">
            {include file="public/page-header"/}
            <!-- end::page-header -->
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-body">
                            <div class="app-block">
                                <div class="app-content">
                                    <div class="app-action">
                                        <div class="input-group" style="width: 130px">
                                            <input type="text" name="name" id="name" autofocus="autofocus" class="form-control" placeholder="顶级分类">
                                        </div>

                                        &nbsp;<div class="action-left">
                                            <ul class="list-inline">
                                                <li class="list-inline-item mb-0">
                                                    <a href="javascript:void(0);" onclick="add()" class="btn btn-secondary ">
                                                        <i data-feather="plus" class="mr-2"></i>
                                                        添加                                                                                                      </a>
                                                </li>

                                            </ul>
                                        </div>
                                        <div class="action-right">
                                            <a href="#" class="app-sidebar-menu-button btn btn-outline-light">
                                                <i data-feather="menu"></i>
                                            </a>
                                            <div class="input-group">
                                                <input type="text" name="keywords" id="keywords" autofocus="autofocus" value="{$Request.get.keywords}"  class="form-control" placeholder="搜索关键字[分类名称]"
                                                       aria-describedby="button-addon1">
                                                <div class="input-group-append">
                                                    <button class="btn btn-outline-light" type="submit" id="button-addon1">
                                                        <i data-feather="search"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                                <table id="linkstable" lay-filter="linkstable"></table>
                        </div>
                    </div>



                </div>
            </div>
        </div>
    </main>
    {include file="public/footer"/}
</div>
<script type="text/html" id="barDemo">
    <button lay-event="edit" id="edits" data="{{d.name}}" data-id="{{d.id}}" class="btn btn-sm btn-outline-secondary">编辑</button><br>
    {{#  if(d.pid < 1){ }}
        <button onclick="add_sub({{d.id}})" class="btn btn-sm btn-outline-secondary">添加子栏目</button><br>
    {{#  } }}

    {{#  if(d.pid >= 1){ }}
        <button onclick="del({{d.id}},{{d.pid}})" class="btn btn-sm btn-outline-secondary">删除</button>
    {{#  } }}

</script>
<script src="__STATIC__/assets/js/custom.js"></script>

<script>
    function add() {
        var val = $('#name').val();
        console.log(val,val.length);
        if (val.length >= 1) {
            $.ajax({
                url:'{:url("/systemsett/cateAdd")}',
                type:'post',
                data:{name:val},
                dataType:'json',
                success:function (res) {
                    if (res.code != 1) {
                        toastr.error(res.msg);
                    } else {
                        toastr.success(res.msg);
                    }
                }
            });
        }
    }

    function add_sub(id) {
        if (!id) {
            return false;
        }
        //prompt层
        layer.prompt({title: '添加子栏目'}, function(value, index){
            console.log(value);
            $.ajax({
                url:'{:url("/systemsett/addSubCate")}',
                type:'post',
                data:{pid:id,name:value},
                dataType:'json',
                success:function (res) {
                    // console.log(res,res.msg);
                    if (res.code != 1) {
                        toastr.error(res.msg);
                    } else {
                        toastr.success(res.msg);
                    }
                }
            });
            layer.close(index);
        });
    }

    $(document).on('click','#edits',function () {
        var data = $(this).attr('data');
        var id = $(this).attr('data-id');
        console.log(id)
        //prompt层
        layer.prompt({title: '编辑',value: data}, function(value, index){
            console.log(value);
            $.ajax({
                url:'{:url("/systemsett/cateEdit")}',
                type:'post',
                data:{id:id,name:value},
                dataType:'json',
                success:function (res) {
                    // console.log(res,res.msg);
                    if (res.code != 1) {
                        toastr.error(res.msg);
                    } else {
                        // toastr.success(res.msg);
                        window.location.reload();
                    }
                }
            });
            layer.close(index);
        });
    });

    function del(id,pid) {
        layer.confirm('删除该数据?', {icon: 3, title:'提示'}, function(index){
            $.post("{:url('/systemsett/cateDel')}", {id:id,pid:pid}, function(data) {
                if(data['code']!=1)
                {
                    toastr.error(res.msg);
                }else{
                    // toastr.success(res.msg);
                    window.location.reload();
                }
            });
            layer.close(index);
        })
    }

    // 表格加载
    layui.config({
        base: '__STATIC__/vendors/layui/'
    }).extend({
        treetable: 'treetable-lay/treetable'
    }).use(['layer', 'table', 'treetable','form','jquery'], function () {
        var $ = layui.jquery;
        var table = layui.table;
        var form = layui.form;
        // var element = layui.element;
        var layer = layui.layer;
        var treetable = layui.treetable;

        // treetable 本身不支持 post 方式，故写之
        $.ajax({
            url: '{:url("/systemsett/cate")}',
            type: 'post',
            dataType: 'json',
            success: function(res) {
                // console.log(res.data.list)
                renderTable(res.data.list);
            }
        });

        // 渲染表格
        var renderTable = function (data) {
            console.log(data)
            layer.load(2);
            treetable.render({
                treeColIndex: 1, // 树形图标显示在第几列
                treeSpid: 0, // 最上级的父级id
                treeIdName: 'id',// id字段的名称
                treePidName: 'pid', // pid字段的名称
                treeDefaultClose: true,// 是否默认折叠
                treeLinkage: false,// 父级展开时是否自动展开所有子级
                elem: '#linkstable',
                data:data,
                // toolbar:'#barDemo',
                page: true,
                tree: {
                    arrowType: 'arrow2',   // 自定义箭头风格
                    getIcon: function(d) {  // 自定义图标
                        console.log(d)
                        // d是当前行的数据
                        if (d.haveChild) {  // 判断是否有子集
                            return '<i class="ew-tree-icon ew-tree-icon-folder"></i>';
                        } else {
                            return '<i class="ew-tree-icon ew-tree-icon-file"></i>';
                        }
                    }
                },
                cols: [[
                    {field: 'id', title: 'ID'},
                    {field: 'name', title: '分类名称'},
                    {field: 'cate_count', title: '分类统计'},
                    {field: 'create_time', title: '创建时间'},
                    {templet: '#barDemo', title: '操作'}
                ]],
                done: function (res) {
                    console.log(res)
                    layer.closeAll('loading');
                }
            });
        };

        // renderTable();

        //全部展开
        // $(document).on("click","#btn-expand",function(){
        //     treetable.expandAll('#table1');
        // });
        //
        // //全部折叠
        // $(document).on("click","#btn-fold",function(){
        //     treetable.foldAll('#table1');
        // });

        // //刷新表格
        // $(document).on("click","#btn-refresh",function(){
        //     renderTable();
        // });

        //搜索
        $(document).on("click","#button-addon1",function(){
            var keyword = $('#keywords').val();
            console.log(keyword,$('#table1'),$('#linkstable'))
            var searchCount = 0;
            $('#linkstable').next('.treeTable').find('.layui-table-body tbody tr td').each(function () {
                console.log('进来了')
                $(this).css('background-color', 'transparent');
                var text = $(this).text();
                if (keyword != '' && text.indexOf(keyword) >= 0) {
                    $(this).css('background-color', 'rgb(118 204 254)');
                    if (searchCount == 0) {
                        treetable.expandAll('#linkstable');
                        $('html,body').stop(true);
                        $('html,body').animate({scrollTop: $(this).offset().top - 150}, 500);
                    }
                    searchCount++;
                }
            });
            if (keyword == '') {
                toastr.error("请输入搜索内容");
            } else if (searchCount == 0) {
                toastr.error("没有匹配结果");
            }
        });

        //头工具栏事件
        table.on('toolbar(table1)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);

            switch(obj.event){
                case 'add':
                    layer.ready(function(){
                        layer.open({
                            type: 2,
                            title: '增加',
                            maxmin: true,
                            area: ['80%', '70%'],
                            content: '{:url('add')}',
                            cancel: function(){ //刷新网页
                                //重新加载表格数据
                                self.location='{:url('index')}';
                            }
                        });
                    });
                    //toastr.error('增加' + obj.config.id);
                    break;
                case 'edit':
                    var data = checkStatus.data;
                    var dataall = '';
                    //data = JSON.stringify(data);
                    //循环把所有要删除的ID整成12,13,545
                    for(var i=0;i<data.length;i++){
                        dataall += data[i].id+",";
                    }
                    dataall=dataall.substring(0,dataall.length-1)

                    //         console.log(dataall)
                    //         layer.alert(dataall);
                    break;
                case 'del':
                    var data = checkStatus.data;
                    var dataall = '';
                    //data = JSON.stringify(data);
                    //循环把所有要删除的ID整成12,13,545
                    for(var i=0;i<data.length;i++){
                        dataall += data[i].id+",";
                    }
                    dataall=dataall.substring(0,dataall.length-1)

                    //         console.log(dataall)
                    layer.alert(dataall);
                    break;
            };
        });

        //监听工具条
        table.on('tool(table1)', function (obj) {
            var data = obj.data;
            console.log(data)
            var layEvent = obj.event;

            if (layEvent === 'del') {
                toastr.error('删除' + data.id);
            } else if (layEvent === 'edit') {
                toastr.error('修改' + data.id);
            }
        });


    });
</script>
